<template>
	<view class="container">

		<!-- 表单内容 -->
		<view class="form-content">
			<!-- 第一部分 -->
			<view class="form-section">
				<u-form :model="form" ref="uForm" labelWidth="70px">
					<u-form-item label="联系电话:" prop="phone">
						<u-input v-model="form.phone" placeholder="请输入联系电话" />
					</u-form-item>
					<u-form-item label="现居区域:" prop="area">
						<u-input v-model="form.area" placeholder="请选择居住区域" type="select"
							@click="showAreaPicker = true" />
					</u-form-item>
				</u-form>
			</view>

			<!-- 第二部分 -->
			<view class="form-section">
				<u-form :model="form" ref="uForm" labelWidth="70px">
					<u-form-item label="我的教龄:" prop="teachingAge">
						<u-picker :show="showTeachingAgePicker" ref="teachingAgePicker" :columns="teachingAgeColumns"
							@confirm="confirmTeachingAge" @cancel="cancelTeachingAge"></u-picker>
						<u-button @click="showTeachingAgePicker = true" class="margin-btn select-btn">
							<text class="btn-text">{{ form.teachingAge || "选择历史教龄" }}</text>
							<text class="jtou iconfont-v2 icon-f11-copy"></text>
						</u-button>
					</u-form-item>
					<u-form-item label="家教方式:" prop="teachingMethod">
						<u-picker :show="showTeachingMethodPicker" ref="teachingMethodPicker"
							:columns="teachingMethodColumns" @confirm="confirmTeachingMethod"
							@cancel="cancelTeachingMethod"></u-picker>
						<u-button @click="showTeachingMethodPicker = true" class="margin-btn select-btn">
							<text class="btn-text">{{ form.teachingMethod || "选择可教方式" }}</text>
							<text class="jtou iconfont-v2 icon-f11-copy"></text>
						</u-button>
					</u-form-item>
					<u-form-item label="上门区域:" prop="visitArea">
						<u-input v-model="form.visitArea" placeholder="选择可教区域" type="select"
							@click="showVisitAreaPicker = true" />
						<view class="reset-buttons">
							<!-- <u-button size="mini" @click="resetVisitArea">重新定位</u-button> -->
							<text class="iconfont-v2 icon-dingwei" @click="resetVisitArea"></text>

							<u-button size="mini" @click="clearVisitArea">清空区域</u-button>
						</view>
					</u-form-item>
					<u-form-item label="家教科目:" prop="subject" @click="onChooseSubject">
						<!-- <u-input v-model="form.subject" placeholder="选择擅长科目" type="select" @click="onChooseSubject" /> -->
						<u-button @click="onChooseSubject" class="margin-btn select-btn">
							<text class="btn-text">{{ form.subject || "选择擅长科目" }}</text>
							<text class="jtou iconfont-v2 icon-f11-copy"></text>
						</u-button>
					</u-form-item>
					<u-form-item label="起步薪酬:" prop="salary">
						<u-picker :show="showSalaryPicker" ref="salaryPicker" :columns="salaryColumns"
							@confirm="confirmSalary" @cancel="cancelSalary"></u-picker>
						<u-button @click="showSalaryPicker = true" class="margin-btn select-btn">
							<text class="btn-text">{{ form.salary || "最低薪酬要求" }}</text>
							<text class="jtou iconfont-v2 icon-f11-copy"></text>
						</u-button>
					</u-form-item>
				</u-form>
			</view>

			<!-- 第三部分 -->
			<view class="form-section">
				<view class="label">选择您的家教时间</view>
				<view class="time-grid">
					<view class="time-row">
						<view class="time-cell">&nbsp;</view>
						<view v-for="day in daysOfWeek" :key="day" class="time-cell">{{ day }}</view>
					</view>
					<view v-for="(period, index) in timePeriods" :key="index" class="time-row">
						<view class="time-cell">{{ period }}</view>
						<view v-for="day in daysOfWeek" :key="day" class="time-cell">
							<u-icon :name="form.timeTable[index][day] ? 'checkmark' : 'close'"
								:color="form.timeTable[index][day] ? '#4caf50' : '#ffeae9'" size="16"
								@click="toggleTime(index, day)"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-button">
			<u-button type="warning" @click="nextStep">下一步</u-button>
		</view>

		<!-- 弹出选择器 -->
		<u-picker v-model="showAreaPicker" mode="region" @confirm="confirmArea"></u-picker>
		<u-picker v-model="showVisitAreaPicker" :range="visitAreas" @confirm="confirmVisitArea"></u-picker>

		<!-- 多选科目弹窗 -->
		<u-popup :show="showSubjectPicker" mode="bottom" height="90vh" border-radius="20">
			<view class="subject-picker">
				<view class="picker-header">
					<view class="header-left" @click="cancelSubjectSelection">
						<text class="cancel-btn">取消</text>
					</view>
					<view class="header-title">选择科目</view>
					<view class="header-right" @click="confirmSubjectSelection">
						<text class="confirm-btn">确定选择</text>
					</view>
				</view>

				<view class="selected-count">已选择{{ selectedSubjects.length }}个科目</view>

				<view class="picker-content">
					<view class="category-sidebar">
						<view v-for="(category, index) in subjectCategories" :key="index" class="category-item"
							:class="{ active: currentCategoryIndex === index }" @click="selectCategory(index)">
							{{ category.name }}
						</view>
					</view>

					<view class="subjects-grid">
						<view v-for="(subject, index) in currentSubjects" :key="index" class="subject-item"
							:class="{ selected: selectedSubjects.includes(subject) }" @click="toggleSubject(subject)">
							{{ subject }}
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		submitTeacherOrder
	} from '@/utils/mockApi.js';
	import * as api from '@/api/family'
	export default {
		data() {
			return {
				form: {
					phone: '',
					area: '',
					teachingAge: '',
					teachingMethod: '',
					visitArea: '',
					subject: '',
					salary: '',
					timeTable: [{
							周一: false,
							周二: false,
							周三: false,
							周四: false,
							周五: false,
							周六: false,
							周日: false
						},
						{
							周一: false,
							周二: false,
							周三: false,
							周四: false,
							周五: false,
							周六: false,
							周日: false
						},
						{
							周一: false,
							周二: false,
							周三: false,
							周四: false,
							周五: false,
							周六: false,
							周日: false
						}
					],
					// 地址相关字段
					longitude: '',
					latitude: '',
					regionProvince: '',
					regionCity: '',
					regionDistrict: ''
				},
				showAreaPicker: false,
				showTeachingAgePicker: false,
				showTeachingMethodPicker: false,
				showVisitAreaPicker: false,
				showSubjectPicker: false,
				showSalaryPicker: false,

				// 教龄选择器数据
				teachingAgeColumns: [
					['1年以下', '1-2年', '3-5年', '5-10年', '10年以上']
				],

				// 家教方式选择器数据
				teachingMethodColumns: [
					['线上', '线下', '线上+线下']
				],

				// 薪酬选择器数据
				salaryColumns: [
					['60元/小时', '80元/小时', '100元/小时', '120元/小时', '150元/小时', '200元/小时', '面议']
				],

				visitAreas: ['区域1', '区域2', '区域3'],
				daysOfWeek: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
				timePeriods: ['上午', '下午', '晚上'],
				// 科目选择相关数据
				selectedSubjects: [],
				currentCategoryIndex: 0,
				subjectCategories: []
			};
		},
		computed: {
			currentSubjects() {
				return this.subjectCategories[this.currentCategoryIndex]?.subjects || [];
			}
		},
		onShow() {
			this.getSub()
		},
		methods: {
			getSub(){
				api.getCatAndCourseApi().then(res=>{
					let list = res.data
					if(list.length>0){
						for (var index = 0; index < list.length; index++) {
							let subTemp = {name:"",subjects:[]}
							subTemp.name = (list[index]['name']);
							let courseList = list[index]['list']
							if(courseList.length>0){
								let temp = [];
								for (var i = 0; i < courseList.length; i++) {
									temp.push(courseList[i]['name'])
								}
								subTemp.subjects = temp
							}else{
								subTemp.subjects = []
							}
							this.subjectCategories.push(subTemp)
						}
					}
				})
			},
			onChooseSubject() {
				console.log('onChooseSubject');
				this.showSubjectPicker = true;
			},
			goBack() {
				uni.navigateBack();
			},

			/**
			 * 验证表单数据
			 * @returns {boolean}
			 */
			validateForm() {
				if (!this.form.phone) {
					uni.showToast({
						title: '请填写联系电话',
						icon: 'none'
					});
					return false;
				}

				// 简单的手机号验证
				const phoneReg = /^1[3-9]\d{9}$/;
				if (!phoneReg.test(this.form.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return false;
				}

				if (!this.form.area) {
					uni.showToast({
						title: '请选择现居区域',
						icon: 'none'
					});
					return false;
				}

				if (!this.form.teachingAge) {
					uni.showToast({
						title: '请选择教龄',
						icon: 'none'
					});
					return false;
				}

				if (!this.form.teachingMethod) {
					uni.showToast({
						title: '请选择家教方式',
						icon: 'none'
					});
					return false;
				}

				if (!this.form.subject) {
					uni.showToast({
						title: '请选择家教科目',
						icon: 'none'
					});
					return false;
				}

				if (!this.form.salary) {
					uni.showToast({
						title: '请选择起步薪酬',
						icon: 'none'
					});
					return false;
				}

				// 验证是否至少选择了一个时间段
				const hasSelectedTime = this.form.timeTable.some(row => {
					return Object.values(row).some(val => val === true);
				});

				if (!hasSelectedTime) {
					uni.showToast({
						title: '请至少选择一个家教时间',
						icon: 'none'
					});
					return false;
				}

				return true;
			},

			/**
			 * 提交表单数据
			 */
			async nextStep() {
				// 验证表单
				if (!this.validateForm()) {
					return;
				}

				// 显示加载提示
				uni.showLoading({
					title: '提交中...',
					mask: true
				});

				try {
					// 准备提交的数据，按照接口文档的字段要求
					const submitData = {
						phone: this.form.phone || '',
						area: this.form.area || '',
						teachingAge: this.form.teachingAge || '',
						teachingMethod: this.form.teachingMethod || '',
						visitArea: this.form.visitArea || '',
						salary: this.form.salary || '',
						timeTable: JSON.stringify(this.form.timeTable),
						selectedSubjects: JSON.stringify(this.selectedSubjects),
						// 地址相关字段
						longitude: this.form.longitude || '',
						latitude: this.form.latitude || '',
						regionProvince: this.form.regionProvince || '',
						regionCity: this.form.regionCity || '',
						regionDistrict: this.form.regionDistrict || ''
					};
					
					// 移除空字符串字段（可选）
					Object.keys(submitData).forEach(key => {
						if (submitData[key] === '') {
							delete submitData[key];
						}
					});
					
					// 调用API提交数据
					await api.insertTeacherApi(submitData).then(response=>{
						uni.hideLoading();
						
						if (response.code === 200) {
							// 提交成功
							uni.showToast({
								title: response.message || '提交成功',
								icon: 'success',
								duration: 2000
							});
						
							// 延迟跳转到自我介绍页面或订单详情页面
							setTimeout(() => {
								uni.navigateTo({
									url: `/pages/jiajiao/teacher_intro?orderId=${response.data.id}`
								});
							}, 1000);
						} else {
							// 提交失败
							uni.showModal({
								title: '提交失败',
								content: response.message || '提交失败，请重试',
								showCancel: false
							});
						}
					});

					
				} catch (error) {
					uni.hideLoading();
					console.error('提交订单失败:', error);
					uni.showModal({
						title: '提交失败',
						content: '网络错误，请检查网络后重试',
						showCancel: false
					});
				}
			},
			resetVisitArea() {
				let that = this
				// 重新定位逻辑
				uni.chooseLocation({
					success: (res) => {
						console.log("获取定位成功", res)
						let form = {
							longitude:res.longitude,
							latitude: res.latitude
						}
						that.form.longitude = res.longitude;
						that.form.latitude = res.latitude;
						api.addressAnalysis(form).then( data =>{
							
							that.form.regionCity = data.data.address_component.city;
							that.form.regionDistrict =  data.data.address_component.district;
							that.form.regionProvince = data.data.address_component.province;  
							
						});
						this.form.visitArea = res.name;
					},
					fail: (err) => {
						uni.showToast({
							title: '获取定位失败',
							icon: 'none'
						});
					}
				})
			},
			clearVisitArea() {
				this.form.visitArea = '';
			},
			confirmArea(e) {
				this.form.area = e.result.join(' ');
			},

			// 教龄选择相关方法
			confirmTeachingAge(e) {
				this.form.teachingAge = e.value[0];
				this.showTeachingAgePicker = false;
			},

			cancelTeachingAge() {
				this.showTeachingAgePicker = false;
			},

			// 家教方式选择相关方法
			confirmTeachingMethod(e) {
				this.form.teachingMethod = e.value[0];
				this.showTeachingMethodPicker = false;
			},

			cancelTeachingMethod() {
				this.showTeachingMethodPicker = false;
			},
			confirmVisitArea(e) {
				this.form.visitArea = this.visitAreas[e.index];
			},
			// 科目选择相关方法
			selectCategory(index) {
				this.currentCategoryIndex = index;
			},
			toggleSubject(subject) {
				const index = this.selectedSubjects.indexOf(subject);
				if (index > -1) {
					this.selectedSubjects.splice(index, 1);
				} else {
					this.selectedSubjects.push(subject);
				}
			},
			confirmSubjectSelection() {
				if (this.selectedSubjects.length === 0) {
					uni.showToast({
						title: '请至少选择一个科目',
						icon: 'none'
					});
					return;
				}
				this.form.subject = this.selectedSubjects.join('、');
				this.showSubjectPicker = false;
				uni.showToast({
					title: `已选择${this.selectedSubjects.length}个科目`,
					icon: 'success'
				});
			},
			cancelSubjectSelection() {
				this.showSubjectPicker = false;
				// 可以选择是否清空已选择的科目
				// this.selectedSubjects = [];
			},
			// 薪酬选择相关方法
			confirmSalary(e) {
				this.form.salary = e.value[0];
				this.showSalaryPicker = false;
			},

			cancelSalary() {
				this.showSalaryPicker = false;
			},
			toggleTime(periodIndex, day) {
				this.$set(this.form.timeTable[periodIndex], day, !this.form.timeTable[periodIndex][day]);
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import "@/uni.scss";

	.container {
		padding: 30rpx;
		padding-bottom: 150rpx;
		/* 为底部固定按钮留出空间 */
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #00c8c8;
		padding: 10px 20px;
		color: #fff;
	}

	.header-title {
		font-size: 18px;
		font-weight: bold;
	}

	.form-section {
		border: 1px solid #e5e5e5;
		border-radius: 8rpx;
		padding: 30rpx;
		// margin: 16px;
		background-color: #ffffff;
		margin-bottom: 20rpx;
	}

	.submit-button {
		margin-top: 20rpx;
	}

	.reset-buttons {
		display: flex;
		gap: 20rpx;
		align-items: center;
		margin-left: 20rpx;
	}

	/* 确保按钮和输入框高度一致 */
	.reset-buttons .u-button {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 24rpx;
	}

	/* 统一输入框和按钮高度 */
	::v-deep .u-input {
		height: 80rpx;
	}

	::v-deep .u-input__content {
		height: 80rpx;
	}

	::v-deep .u-input__content__field-wrapper__field {
		height: 80rpx;
		line-height: 80rpx;
	}

	.label {
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.time-grid {
		display: grid;
		grid-template-columns: repeat(8, 1fr);
		border: 1rpx solid #ccc;
		border-collapse: collapse;
	}

	.time-row {
		display: contents;
	}

	.time-cell {
		border: 1rpx solid #e0e0e0;
		text-align: center;
		padding: 8rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 0;
		color: #666;
		font-size: 24rpx;
		font-weight: normal;
	}

	/* 第一行背景色 */
	.time-row:first-child .time-cell {
		background-color: #f0f0f0;
		font-weight: bold;
	}

	/* 第一列背景色 */
	.time-cell:first-child {
		background-color: #f0f0f0;
		font-weight: bold;
	}

	/* 第一行第一列的交集 */
	.time-row:first-child .time-cell:first-child {
		background-color: #f0f0f0;
	}

	::v-deep .form-section .u-form-item__body__left__content__label,
	::v-deep .form-section .u-form-item__body__left__content {
		font-size: 24rpx !important;
		/* font-weight: bold !important; */
	}

	/* 统一输入框字体大小 */
	::v-deep .uni-input-input {
		font-size: 24rpx;
	}

	/* 统一placeholder字体大小 */
	::v-deep .uni-input-placeholder {
		font-size: 24rpx;
	}

	/* uview输入框placeholder样式 */
	::v-deep .u-input__content__field-wrapper__field::placeholder {
		font-size: 24rpx;
	}

	::v-deep .u-form-item__body__right {
		margin-left: 10rpx !important;
	}

	::v-deep .uni-input-input {
		font-size: 24rpx;
	}

	/* 科目选择弹窗样式 */
	.subject-picker {
		height: 100%;
		max-height: 90vh;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		overflow: hidden;
	}

	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		background-color: #fff;
		flex-shrink: 0;
	}

	.header-left,
	.header-right {
		flex: 1;
	}

	.header-right {
		text-align: right;
	}

	.header-title {
		flex: 2;
		text-align: center;
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}

	.cancel-btn,
	.confirm-btn {
		font-size: 24rpx;
		color: #ff6b35;
		padding: 8rpx 16rpx;
	}

	.selected-count {
		padding: 15rpx 30rpx;
		font-size: 24rpx;
		color: #666;
		background-color: #f8f8f8;
		text-align: center;
		flex-shrink: 0;
		border-bottom: 1rpx solid #e0e0e0;
	}

	.picker-content {
		flex: 1;
		display: flex;
		overflow: hidden;
		min-height: 0;
		max-height: calc(90vh - 120rpx);
	}

	.category-sidebar {
		width: 180rpx;
		max-height: 80vh;
		background-color: #f8f8f8;
		border-right: 1rpx solid #e0e0e0;
		overflow-y: auto;
		flex-shrink: 0;
		-webkit-overflow-scrolling: touch;
	}

	.category-item {
		padding: 20rpx 15rpx;
		font-size: 24rpx;
		color: #666;
		text-align: center;
		border-bottom: 1rpx solid #e0e0e0;
		position: relative;
		transition: all 0.3s ease;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		min-height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.category-item.active {
		color: #ff6b35;
		background-color: #fff;
		font-weight: bold;
	}

	.category-item.active::before {
		content: '';
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 4rpx;
		height: 24rpx;
		background-color: #ff6b35;
		border-radius: 2rpx;
	}

	.subjects-grid {
		flex: 1;
		padding: 20rpx;
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 15rpx;
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		align-content: start;
		min-height: 0;
		max-height: 80vh;
	}

	.subject-item {
		padding: 15rpx 10rpx;
		font-size: 22rpx;
		text-align: center;
		border-radius: 6rpx;
		background-color: #f5f5f5;
		color: #666;
		border: 1rpx solid transparent;
		transition: all 0.3s ease;
		min-height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		word-break: break-all;
		line-height: 1.2;
		box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.05);
	}

	.subject-item.selected {
		background-color: #ff6b35;
		color: #fff;
		border-color: #ff6b35;
		font-weight: bold;
		box-shadow: 0 2rpx 6rpx rgba(255, 107, 53, 0.3);
	}

	.subject-item:active {
		transform: scale(0.95);
	}

	/* 滚动条样式优化 */
	.category-sidebar::-webkit-scrollbar,
	.subjects-grid::-webkit-scrollbar {
		width: 6rpx;
	}

	.category-sidebar::-webkit-scrollbar-track,
	.subjects-grid::-webkit-scrollbar-track {
		background: #f1f1f1;
		border-radius: 3rpx;
	}

	.category-sidebar::-webkit-scrollbar-thumb,
	.subjects-grid::-webkit-scrollbar-thumb {
		background: #c1c1c1;
		border-radius: 3rpx;
	}

	.category-sidebar::-webkit-scrollbar-thumb:hover,
	.subjects-grid::-webkit-scrollbar-thumb:hover {
		background: #a8a8a8;
	}

	/* 下拉选择按钮样式 */
	.margin-btn {
		margin: 5rpx;
	}

	/* 选择按钮样式 */
	.select-btn {
		display: flex;
		justify-content: space-between;
		align-items: center;
		text-align: left;
	}

	.btn-text {
		flex: 1;
		text-align: left;
	}

	.jtou {
		color: #999;
		font-size: 36rpx;
	}
</style>